<?php
/**
 * @title 20. 有效的括号 - 栈
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param String $s
     * @return Boolean
     */
    function isValid($s) {
        /**
         * @since 2020-08-14 栈
         */
        $stacks = [];

        /**
         * @since 2020-08-14 逐位遍历
         */
        for ($i=0, $len=strlen($s); $i<$len; $i++){
            /**
             * @since 2020-08-14 `(`, `[`, `{` 入栈
             */
            switch ($s[$i]){
                case "(":
                case "[":
                case "{":
                    $stacks[] = $s[$i];
                    break;
                default:
                    /**
                     * @since 2020-08-14 `)`, `]`, `}` 出栈
                     */
                    $char = array_pop($stacks);

                    /**
                     * @since 2020-08-14 匹配成功3种情况
                     */
                    if($char === "(" AND $s[$i] === ")"){
                    } elseif($char === "[" AND $s[$i] === "]") {
                    } elseif($char === "{" AND $s[$i] === "}") {
                    } else {
                        /**
                         * @since 2020-08-14 匹配失败
                         */
                        return false;
                        break;
                    }
            }
        }

        /**
         * @return
         */
        if(empty($stacks)){
            return true;
        } else {
            return false;
        }
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.14.php
 */
$datas = [
    "()",
    "([)]",
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->isValid($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
